<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
    // 检查用户是否登录
    Integer userId = (Integer) session.getAttribute("userId");
    if (userId == null) {
        response.sendRedirect("login.jsp");
        return;
    }
%>

<!DOCTYPE html>
<html>
<head>
    <title>收货地址管理 - 淘乐乐商城</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .main-content {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 15px;
            display: flex;
            gap: 20px;
        }
        
        .sidebar {
            width: 250px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 20px;
        }
        
        .content {
            flex: 1;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 20px;
        }
        
        .section-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .add-address-btn {
            background-color: #ff4d4f;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .add-address-btn:hover {
            background-color: #ff6b6b;
        }
        
        .address-list {
            display: grid;
            gap: 15px;
        }
        
        .address-card {
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
            position: relative;
        }
        
        .address-card.default {
            border-color: #ff4d4f;
        }
        
        .default-tag {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #ff4d4f;
            color: white;
            padding: 2px 8px;
            border-radius: 2px;
            font-size: 12px;
        }
        
        .receiver-info {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .address-detail {
            color: #666;
            margin-bottom: 15px;
        }
        
        .address-actions {
            display: flex;
            gap: 10px;
        }
        
        .address-actions button {
            border: 1px solid #ddd;
            background: white;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .address-actions button:hover {
            border-color: #ff4d4f;
            color: #ff4d4f;
        }
        
        .address-form {
            display: none;
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #eee;
            border-radius: 4px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            border-color: #ff4d4f;
            outline: none;
        }
        
        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .save-btn {
            background-color: #ff4d4f;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .cancel-btn {
            background-color: white;
            border: 1px solid #ddd;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .save-btn:hover {
            background-color: #ff6b6b;
        }
        
        .cancel-btn:hover {
            border-color: #ff4d4f;
            color: #ff4d4f;
        }
    </style>
</head>
<body>
    <%@ include file="header.jsp" %>
    
    <div class="main-content">
        <div class="sidebar">
            <ul class="sidebar-menu">
                <li>
                    <a href="profile.jsp">
                        <i class="fas fa-user"></i>
                        个人信息
                    </a>
                </li>
                <li>
                    <a href="my-orders.jsp">
                        <i class="fas fa-shopping-bag"></i>
                        我的订单
                    </a>
                </li>
                <li>
                    <a href="address.jsp" class="active">
                        <i class="fas fa-map-marker-alt"></i>
                        收货地址
                    </a>
                </li>
                <li>
                    <a href="favorites.jsp">
                        <i class="fas fa-heart"></i>
                        我的收藏
                    </a>
                </li>
                <li>
                    <a href="account-settings.jsp">
                        <i class="fas fa-cog"></i>
                        账号设置
                    </a>
                </li>
            </ul>
        </div>
        
        <div class="content">
            <div class="section-title">
                <span>收货地址</span>
                <button class="add-address-btn" onclick="showAddressForm()">
                    <i class="fas fa-plus"></i>
                    新增地址
                </button>
            </div>
            
            <div style="display: none;">
                地址数量: ${addresses.size()}
            </div>
            
            <div class="address-list">
                <c:if test="${empty addresses}">
                    <div class="empty-address">
                        <i class="fas fa-map-marker-alt"></i>
                        <p>暂无收货地址，请添加</p>
                    </div>
                </c:if>
                <c:forEach var="address" items="${addresses}">
                    <div class="address-card ${address.isDefault ? 'default' : ''}">
                        <c:if test="${address.isDefault}">
                            <span class="default-tag">默认地址</span>
                        </c:if>
                        <div class="receiver-info">
                            ${address.receiver} ${address.phone}
                        </div>
                        <div class="address-detail">
                            ${address.province} ${address.city} ${address.district} ${address.detailAddress}
                        </div>
                        <div class="address-actions">
                            <button onclick="editAddress(${address.addressId})">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button onclick="deleteAddress(${address.addressId})">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                            <c:if test="${!address.isDefault}">
                                <button onclick="setDefaultAddress(${address.addressId})">
                                    <i class="fas fa-check"></i> 设为默认
                                </button>
                            </c:if>
                        </div>
                    </div>
                </c:forEach>
            </div>
            
            <style>
                .empty-address {
                    text-align: center;
                    padding: 40px 0;
                    color: #999;
                }
                
                .empty-address i {
                    font-size: 48px;
                    margin-bottom: 10px;
                }
                
                .address-card {
                    background: #fff;
                    border: 1px solid #e8e8e8;
                    border-radius: 4px;
                    padding: 20px;
                    margin-bottom: 15px;
                    position: relative;
                }
                
                .address-card.default {
                    border-color: #ff4d4f;
                }
                
                .default-tag {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                    background: #ff4d4f;
                    color: white;
                    padding: 2px 8px;
                    border-radius: 2px;
                    font-size: 12px;
                }
                
                .receiver-info {
                    font-size: 16px;
                    font-weight: bold;
                    margin-bottom: 10px;
                }
                
                .address-detail {
                    color: #666;
                    margin-bottom: 15px;
                }
                
                .address-actions {
                    display: flex;
                    gap: 10px;
                }
                
                .address-actions button {
                    padding: 5px 10px;
                    border: 1px solid #ddd;
                    background: white;
                    border-radius: 4px;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    gap: 5px;
                }
                
                .address-actions button:hover {
                    border-color: #ff4d4f;
                    color: #ff4d4f;
                }
            </style>
            
            <!-- 地址表单 -->
            <div id="addressForm" class="address-form">
                <form id="saveAddressForm" onsubmit="return saveAddress(event)">
                    <input type="hidden" id="addressId" name="addressId">
                    <div class="form-group">
                        <label for="receiver">收货人</label>
                        <input type="text" id="receiver" name="receiver" required>
                    </div>
                    <div class="form-group">
                        <label for="phone">手机号码</label>
                        <input type="tel" id="phone" name="phone" pattern="[0-9]{11}" required>
                    </div>
                    <div class="form-group">
                        <label for="province">省份</label>
                        <select id="province" name="province" required>
                            <option value="">请选择省份</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="city">城市</label>
                        <select id="city" name="city" required>
                            <option value="">请选择城市</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="district">区/县</label>
                        <select id="district" name="district" required>
                            <option value="">请选择区/县</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="detailAddress">详细地址</label>
                        <input type="text" id="detailAddress" name="detailAddress" required>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="isDefault" name="isDefault">
                            设为默认地址
                        </label>
                    </div>
                    <div class="form-actions">
                        <button type="button" class="cancel-btn" onclick="hideAddressForm()">取消</button>
                        <button type="submit" class="save-btn">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <%@ include file="footer.jsp" %>
    
    <script>
        // 省市区数据
        const areaData = {
            '北京市': {
                '北京市': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区']
            },
            '上海市': {
                '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '闵行区', '宝山区', '嘉定区', '浦东新区', '金山区', '松江区', '青浦区', '奉贤区', '崇明区']
            },
            '广东省': {
                '广州市': ['越秀区', '海珠区', '荔湾区', '天河区', '白云区', '黄埔区', '番禺区', '花都区', '南沙区', '从化区', '增城区'],
                '深圳市': ['福田区', '罗湖区', '南山区', '盐田区', '宝安区', '龙岗区', '龙华区', '坪山区', '光明区'],
                '珠海市': ['香洲区', '斗门区', '金湾区'],
                '东莞市': ['莞城区', '东城区', '南城区', '万江区', '石碣镇', '石龙镇', '茶山镇', '石排镇', '企石镇', '横沥镇', '桥头镇', '谢岗镇', '东坑镇', '常平镇', '寮步镇', '大朗镇', '黄江镇', '清溪镇', '塘厦镇', '凤岗镇', '长安镇']
            },
            '浙江省': {
                '杭州市': ['上城区', '下城区', '江干区', '拱墅区', '西湖区', '滨江区', '萧山区', '余杭区', '富阳区', '临安区', '钱塘区', '临平区'],
                '宁波市': ['海曙区', '江北区', '北仑区', '镇海区', '鄞州区', '奉化区', '余姚市', '慈溪市', '象山县', '宁海县'],
                '温州市': ['鹿城区', '龙湾区', '瓯海区', '洞头区', '永嘉县', '平阳县', '苍南县', '文成县', '泰顺县', '瑞安市', '乐清市']
            }
            // 可以继续添加其他省份和城市数据
        };
        
        // 初始化省份下拉列表
        function initProvinces() {
            const provinceSelect = document.getElementById('province');
            provinceSelect.innerHTML = '<option value="">请选择省份</option>';
            
            for (const province in areaData) {
                const option = document.createElement('option');
                option.value = province;
                option.textContent = province;
                provinceSelect.appendChild(option);
            }
        }
        
        // 更新城市下拉列表
        function updateCities() {
            const province = document.getElementById('province').value;
            const citySelect = document.getElementById('city');
            const districtSelect = document.getElementById('district');
            
            citySelect.innerHTML = '<option value="">请选择城市</option>';
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            
            if (province && areaData[province]) {
                for (const city in areaData[province]) {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);
                }
            }
        }
        
        // 更新区县下拉列表
        function updateDistricts() {
            const province = document.getElementById('province').value;
            const city = document.getElementById('city').value;
            const districtSelect = document.getElementById('district');
            
            districtSelect.innerHTML = '<option value="">请选择区/县</option>';
            
            if (province && city && areaData[province][city]) {
                for (const district of areaData[province][city]) {
                    const option = document.createElement('option');
                    option.value = district;
                    option.textContent = district;
                    districtSelect.appendChild(option);
                }
            }
        }
        
        // 添加事件监听器
        document.getElementById('province').addEventListener('change', updateCities);
        document.getElementById('city').addEventListener('change', updateDistricts);
        
        // 页面加载时初始化省份列表
        initProvinces();
        
        // 编辑地址时，设置省市区的选中状态
        function setAreaSelections(province, city, district) {
            document.getElementById('province').value = province;
            updateCities();
            document.getElementById('city').value = city;
            updateDistricts();
            document.getElementById('district').value = district;
        }
        
        // 显示地址表单
        function showAddressForm() {
            document.getElementById('addressForm').style.display = 'block';
            document.getElementById('addressId').value = '';
            document.getElementById('saveAddressForm').reset();
            initProvinces(); // 重置省市区选择
        }
        
        // 隐藏地址表单
        function hideAddressForm() {
            document.getElementById('addressForm').style.display = 'none';
        }
        
        // 保存地址
        function saveAddress(event) {
            event.preventDefault();
            
            const formData = new FormData(event.target);
            const addressData = Object.fromEntries(formData.entries());
            
            fetch('address/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(addressData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('地址保存成功');
                    location.reload();
                } else {
                    alert(data.message || '保存失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('保存失败，请重试');
            });
            
            return false;
        }
        
        // 编辑地址
        function editAddress(addressId) {
            fetch(`address/get?addressId=${addressId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const address = data.data;
                    document.getElementById('addressId').value = address.addressId;
                    document.getElementById('receiver').value = address.receiver;
                    document.getElementById('phone').value = address.phone;
                    setAreaSelections(address.province, address.city, address.district);
                    document.getElementById('detailAddress').value = address.detailAddress;
                    document.getElementById('isDefault').checked = address.isDefault;
                    
                    showAddressForm();
                } else {
                    alert(data.message || '获取地址信息失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取地址信息失败');
            });
        }
        
        // 删除地址
        function deleteAddress(addressId) {
            if (confirm('确定要删除这个地址吗？')) {
                fetch(`address/delete?addressId=${addressId}`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('地址删除成功');
                        location.reload();
                    } else {
                        alert(data.message || '删除失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败，请重试');
                });
            }
        }
        
        // 设置默认地址
        function setDefaultAddress(addressId) {
            fetch(`address/setDefault?addressId=${addressId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('默认地址设置成功');
                    location.reload();
                } else {
                    alert(data.message || '设置失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('设置失败，请重试');
            });
        }
    </script>
</body>
</html> 